﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace Nijie.Network
{
    public abstract class BaseSyncCtrl : MonoBehaviour, ISyncListener
    {
        //[SerializeField, Header("是否自定义ID")]
        //bool useCustomID = false;
        [SerializeField, Header("如果自定义ID，在这里填写ID，唯一ID")]
        string ID;
        #region Editor
#if UNITY_EDITOR
        private void Reset()
        {
            ID = GetHashCode().ToString();
        }
#endif
        #endregion Editor
        protected abstract void Deserialize(NetworkReader reader, RemoteDevice remoteDevice);
        protected abstract void Serialize(NetworkWriter writer);
        //bool sync = false;

        string ISyncListener.ID
        {
            get
            {
                return ID;
            }
        }
        //public bool ReadyToSync { get { return sync; } }
        public void OnDeserialize(NetworkReader reader, RemoteDevice remoteDevice)
        {
            //if (reader.ReadBoolean())
            Deserialize(reader, remoteDevice);
        }
        public void OnSerialize(NetworkWriter writer)
        {
            //writer.Write(sync);
            //if (sync)
            Serialize(writer);
            //sync = false;
        }
        /// <summary>
        /// 需要同步时调用
        /// </summary>
        public void Sync()
        {
            SyncManager.SyncListenerData(this);
            //sync = true;
        }
        // Use this for initialization
        public virtual void Awake()
        {
            //        if (useCustomID)
            SyncManager.AddListener(this);
            //else
            //    SyncManager.AddListener(this);
        }
        public virtual void OnDestroy()
        {
            SyncManager.RemoveListener(this);
        }
        //#if UNITY_EDITOR
        public void SetID(string id)
        {
            SyncManager.RemoveListener(this);
            ID = id;
            SyncManager.AddListener(this);
        }
        //public string GetID() { return ID; }
        //#endif
    }
}
